import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@Slf4j
public class SM4Helper {

    /**
     * 指明加密算法和秘钥
     */
    //private static SymmetricCrypto SM4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", "betawsp012345678".getBytes());
    private static SymmetricCrypto SM4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", "scrm001234567890".getBytes());

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encryptSm4(String data) {
        byte[] encrypt = SM4.encrypt(data);
        return new BASE64Encoder().encode(encrypt);
    }

    /**
     * 解密
     *
     * @param data
     * @return
     */
    public static String decryptSm4(String data) {
        try {
            byte[] decrypt = SM4.decrypt(new BASE64Decoder().decodeBuffer(data));
            return new String(decrypt);
        } catch (Exception e) {
            log.error("DecryptSm4 error:{}", data, e);
            return "";
        }
    }

    public static void main(String[] args) {
        System.out.println(SM4Helper.encryptSm4("LiXin"));
    }
}
